package com.lzy.wzy.netty.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 若连续2次无读事件，则关闭这个客户端channel
 *
 * @author sixiaojie
 * @date 2020-08-21-16:14
 */
@Slf4j
public class HeartBeatHandler extends ChannelInboundHandlerAdapter {


    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {

                log.info("读超时触发");
                if (ctx.channel().isActive()) {
                    ctx.channel().writeAndFlush(new TextWebSocketFrame("要断线了"));
                    ctx.channel().close();
                }else {
                    log.info("is not active");
                }
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
